home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C25 / Recycle4.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  71 lines

  1. //: C25:Recycle4.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. //{L} TrashPrototypeInit
  7. //{L} fillBin Trash TrashStatics
  8. // Adding TrashBins and TrashSorters
  9. #include "Trash.h"
  10. #include "Aluminum.h"
  11. #include "Paper.h"
  12. #include "Glass.h"
  13. #include "Cardboard.h"
  14. #include "fillBin.h"
  15. #include "sumValue.h"
  16. #include "../purge.h"
  17. #include <fstream>
  18. #include <vector>
  19. using namespace std;
  20. ofstream out("Recycle4.out");
  21.  
  22. class TBin : public vector<Trash*> {
  23. public:
  24.   virtual bool grab(Trash*) = 0;
  25. };
  26.  
  27. template<class TrashType>
  28. class TrashBin : public TBin {
  29. public:
  30.   bool grab(Trash* t) {
  31.     TrashType* tp = dynamic_cast<TrashType*>(t);
  32.     if(!tp) return false; // Not grabbed
  33.     push_back(tp);
  34.     return true; // Object grabbed
  35.   }
  36. };
  37.  
  38. class TrashSorter : public vector<TBin*> {
  39. public:
  40.   bool sort(Trash* t) {
  41.     for(iterator it = begin(); it != end(); it++)
  42.       if((*it)->grab(t))
  43.         return true;
  44.     return false;
  45.   }
  46.   void sortBin(vector<Trash*>& bin) {
  47.     vector<Trash*>::iterator it;
  48.     for(it = bin.begin(); it != bin.end(); it++)
  49.       if(!sort(*it))
  50.         cerr << "bin not found" << endl;
  51.   }
  52.   ~TrashSorter() { purge(*this); }
  53. };
  54.  
  55. int main() {
  56.   vector<Trash*> bin;
  57.   // Fill up the Trash bin:
  58.   fillBin("Trash.dat", bin);
  59.   TrashSorter tbins;
  60.   tbins.push_back(new TrashBin<Aluminum>());
  61.   tbins.push_back(new TrashBin<Paper>());
  62.   tbins.push_back(new TrashBin<Glass>());
  63.   tbins.push_back(new TrashBin<Cardboard>());
  64.   tbins.sortBin(bin);
  65.   for(TrashSorter::iterator it = tbins.begin(); 
  66.     it != tbins.end(); it++)
  67.     sumValue(**it);
  68.   sumValue(bin);
  69.   purge(bin);
  70. } ///:~
  71.